package io.renren.modules.news.controller;

import io.renren.common.annotation.Login;
import io.renren.common.utils.R;
import io.renren.common.config.ListPageUtils;
import io.renren.common.config.SensitiveWordFilter;
import io.renren.modules.news.entity.Comment;
import io.renren.modules.news.entity.News;
import io.renren.modules.news.entity.reply;
import io.renren.modules.sys.dto.NewsDto;
import io.renren.modules.sys.entity.*;
import io.renren.modules.news.service.NewsService;
import io.renren.modules.sys.service.TokenService;
import io.renren.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Api(tags="新闻接口")
public class NewsController {
    @Autowired
    NewsService newsService;

    @Autowired
    TokenService tokenService;

    @Autowired
    UserService userService;




    /**
     * 查看当前新闻
     */
    @PostMapping("getNews")
    @ApiOperation("查看当前新闻")
    public R  getNews(@RequestBody News news){
        Long newsId = news.getNewsId();
        News newss = newsService.getNews(newsId);
        //增加一个阅读数量
        News n = new News();
        n.setNewsId(newsId);
        int readCount = newss.getReadCount()+ 1;
        n.setReadCount(readCount);

        newsService.updateNewsReadCount(n);


        return  R.ok("查看当前新闻成功",100).put("data",newss);
    }

    /**
     * 查看当前新闻的评论列表
     */
    @PostMapping("getNewsCommentList")
    @ApiOperation("查看当前新闻的评论列表")
    public R getNewsCommentList(@RequestBody NewsDto news){
        /*int pageSize = Integer.parseInt(news.getMap().get("pageSize").toString());
        int pageNum = Integer.parseInt(news.getMap().get("pageNum").toString());*/
        int pageSize = news.getPageSize();
        int pageNum = news.getPageNum();
        Long newsId = news.getNewsId();
        List commentList = newsService.getNewsCommentList(newsId);

        /*//查看当前评论的点赞量
        long commentId = news.getCommentId();
        long commnetLikeCount = newsService.getCommentLikeCount(commentId);*/
        if(commentList.size()>0){
            ListPageUtils pageUtil = new ListPageUtils(commentList,pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if(list.size() > 0){
                for(int i = 0;i<list.size();i++){
                    Comment c = (Comment) list.get(i);
                    c.setUserName(new String(c.getUserNameB()));
                    c.setContent(new String(c.getContentB()));
                }
                return R.ok("查询评论成功",100).put("data",list).put("nextNum",pageNum+1);
            }
            return R.ok("查询评论成功",100).put("data",list).put("nextNum",-1);
        }
        return R.ok("此新闻还没有评论哦",100).put("data",commentList).put("nextNum",-1);
    }

    /**
     * 查看当前新闻和当前评论的回复
     */
    @PostMapping("getThisNewsAndCommentReply")
    @ApiOperation("查看当前新闻的当前评论的回复")
    public R getThisNewsAndCommentReply(@RequestBody NewsDto newsDto){
        List commentList = newsService.getThisNewsAndCommentReply(newsDto);
        int pageSize = newsDto.getPageSize();
        int pageNum = newsDto.getPageNum();
        if(commentList.size()>0){
            ListPageUtils pageUtil = new ListPageUtils(commentList,pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if(list.size() > 0){
                return R.ok("查询回复成功",100).put("data",list).put("nextNum",pageNum+1);
            }
            return R.ok("查询回复成功",100).put("data",list).put("nextNum",-1);
        }
        return R.ok("查询回复成功",100).put("data",commentList).put("nextNum",-1);
    }

    /**
     * 根据type查询新闻
     */
    @PostMapping("getNewsByType")
    @ApiOperation("根据type查询新闻列表")
    public R getNewsByType(@RequestBody Map params){
        String type = params.get("type").toString();
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum",pageNum);
        params.put("pageSize",pageSize);
        params.put("type",type);
        if(type!= null && !"".equals(type)){
            /*List newsList = newsService.getNewsByType(params);
            PageInfo pageInfo = new PageInfo(newsList, 10);*/
            List newsList = newsService.getNewsByType(params);
            if(newsList.size() > 0){
                ListPageUtils pageUtil = new ListPageUtils(newsList,pageSize);
                List list = pageUtil.getPagedList(pageNum);
                if(list.size() > 0){
                    return R.ok("根据条件查询新闻成功",100).put("data",list).put("nextNum",pageNum+1);
                }
                return R.ok("根据条件查询新闻成功",100).put("data",list).put("nextNum",-1);
            }
            return R.ok("根据条件查询新闻成功",100).put("data",newsList).put("nextNum",-1);
            }
        return R.ok("查询条件不能为空",101);
    }


    /**
     * 根据type查询新闻
     */
    @PostMapping("news/getNewsList")
    @Login
    @ApiOperation("根据type查询新闻列表")
    public R getNewsList(@RequestBody Map params,@RequestAttribute("userId") Integer userId){

        return R.ok("查询条件不能为空",101);
    }



    /**
     * 模糊查询新闻
     */
    /*@GetMapping("getNewsLike")
    @ApiOperation("模糊查询新闻")
    public R getNewsLike(@Param("word") String word,@Param("pageNum") int pageNum){
        //String word = (String)map.get("word");
        if(word == null || "".equals(word)){
            return R.ok("查询条件不能为空",101);
        }
        List newsList = newsService.getNewsLike(word,pageNum,10);
       *//* Object pageNum =(String)map.get("pageNum");
        Object pageSize = map.get("pageSize");*//*
        //PageHelper.startPage(pageNum,10);
        if(newsList.size()>0){
            //PageInfo pageInfo = new PageInfo(newsList, 10);
            return R.ok("查询成功",100).put("data",pageInfo);
        }
        return R.ok("没有符合条件的新闻",102);
    }*/

    @PostMapping("getNewsLike")
    @ApiOperation("模糊查询新闻")
    public R getNewsLike(@RequestBody Map<String,Object> params){
        String word = (String)params.get("word");
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum",pageNum);
        params.put("pageSize",pageSize);
        if(word == null || "".equals(word)){
            return R.ok("查询条件不能为空",101);
        }
        List newsList = newsService.getNewsLike(params);
        if(newsList.size() > 0){
            ListPageUtils pageUtil = new ListPageUtils(newsList,pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if(list.size() > 0){
                return R.ok("查询成功",100).put("data",list).put("nextNum",pageNum+1);
            }
            return R.ok("查询成功",100).put("data",list).put("nextNum",-1);
        }
        return R.ok("没有符合条件的新闻",100).put("data",newsList).put("nextNum",-1);
    }


    /**
     * 发表评论
     */
    @Login
    @PostMapping("insertComment")
    @ApiOperation("发表评论")
    public R insertComment(@RequestBody Comment comment){
        if(comment.getContent()!=null && !"".equals(comment.getContent())){
            String token = comment.getToken();
            Long userId = tokenService.getUserIdByToken(token);
            UserEntity user = userService.getUserByUserId(userId);
            String contentNoFilter = comment.getContent();
            comment.setContent("");
            comment.setContentB(wordFilter(contentNoFilter).getBytes());
            comment.setUserId(userId);
            comment.setUserHeadImage(user.getHeadImg());
            comment.setUserName("");
            comment.setUserNameB(user.getNickNameB());
            newsService.insertComment(comment);
            String content = new String(comment.getContentB());
            return R.ok("评论成功",100).put("comment",content);
        }
        return R.error(101,"评论不能为空");
    }


    /**
     * 过滤敏感字符
     * @param str
     */
    public String wordFilter(@RequestBody String str){
        SensitiveWordFilter sw = new SensitiveWordFilter();
        sw.InitializationWork();
        long startNumer = System.currentTimeMillis();
        System.out.println("被检测字符长度:" + str.length());
        str = sw.filterInfo(str);
        long endNumber = System.currentTimeMillis();
        System.out.println("耗时(毫秒):" + (endNumber - startNumer));
        System.out.println("过滤之后:" + str);
        return str;
    }

    /**
     * 回复评论
     */
    @Login
    @PostMapping("insertReply")
    @ApiOperation("发表回复")
    public R insertReply(@RequestBody reply reply){
        if (reply.getContent() != null && !"".equals(reply.getContent())){
            String token = reply.getToken();
            Long userId = tokenService.getUserIdByToken(token);
            UserEntity user = userService.getUserByUserId(userId);
            //敏感字过滤
            reply.setContent(wordFilter(reply.getContent()));
            reply.setUserName(user.getNickName());
            reply.setUserHeadImage(user.getHeadImg());
            reply.setUserId(userId);
            newsService.insertReply(reply);
            return R.ok("回复成功",100);
        }
        return R.error(101,"回复不能为空");
    }

    /**
     * 添加个人新闻收藏
     */
    @Login
    @PostMapping("addUserNewsCollection")
    @ApiOperation("添加个人新闻收藏")
    public R addUserNewsCollection(@RequestBody UserNewsCollection userNewsCollection){
        String token = userNewsCollection.getToken();
        Long userId = tokenService.getUserIdByToken(token);
        userNewsCollection.setUserId(userId);
        newsService.addUserNewsCollection(userNewsCollection);
        return R.ok("添加个人新闻收藏成功",100);
    }


    /**
     * 删除个人新闻收藏
     */
    @Login
    @PostMapping("delUserNewsCollection")
    @ApiOperation("删除个人新闻收藏")
    public R delUserNewsCollection(@RequestBody UserNewsCollection userNewsCollection){
        String token = userNewsCollection.getToken();
        Long userId = tokenService.getUserIdByToken(token);
        userNewsCollection.setUserId(userId);
        newsService.delUserNewsCollection(userNewsCollection);
        return R.ok("删除个人新闻收藏成功",100);
    }

    /**
     * 获取个人新闻收藏列表
     */
    @Login
    @PostMapping("getUserNewsCollection")
    @ApiOperation("获取个人新闻收藏列表")
    public R getUserNewsCollection(@RequestBody Map params){
        String token = (String) params.get("token");
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum",pageNum);
        params.put("pageSize",pageSize);
        Long userId = tokenService.getUserIdByToken(token);
        params.put("userId",userId);
        List newsList = newsService.getUserNewsCollection(params);
        //分页
        if(newsList.size()>0){
            ListPageUtils pageUtil = new ListPageUtils(newsList,pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if(list.size() > 0){
                return R.ok("获取收藏列表成功",100).put("data",list).put("nextNum",pageNum+1);
            }
            return R.ok("获取收藏列表成功",100).put("data",list).put("nextNum",-1);
        }
        return R.ok("收藏列表为空",100).put("data",newsList).put("nextNum",-1);
    }

    /**
     * 判断这个用户是否收藏了本新闻
     */
    @Login
    @PostMapping("checkIsCollectionNews")
    @ApiOperation("判断这个用户是否收藏了本新闻")
    public R checkIsCollectionNews(@RequestBody Map map){
        //传来这个用户的token和新闻的id
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
        List list = newsService.checkIsCollectionNews(map);
        if(list.size() == 0){
            return R.ok("",100).put("data",100);
        }
        return R.ok("",100).put("data",101);
    }

    /**
     * 添加点赞
     */
    @Login
    @PostMapping("saveCommentLike")
    @ApiOperation("添加点赞")
    public R saveCommentLike(@RequestBody Map map){
        /*Long userId = (Long)map.get("userId");
        Long newsId = (Long)map.get("newsId");
        Long commentId = (Long)map.get("commentId");*/
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
        newsService.saveCommentLike(map);
        newsService.updateCommentLike(map);

        return R.ok("点赞成功哦~",100);
    }

        /**
         * 删除点赞
         */
    @Login
    @PostMapping("delCommentLike")
    @ApiOperation("删除点赞")
    public R delCommentLike(@RequestBody Map map){

        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
        newsService.delCommentLike(map);
        newsService.deleteCommentLike(map);
        return R.ok("取消点赞成功~",100);
    }

    /**
     * 判断本条评论是否被当前用户点赞过
     */
    @Login
    @PostMapping("checkCommentLike")
    @ApiOperation("判断本条评论是否被当前用户点赞过")
    public R checkCommentLike(@RequestBody Map map){
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
       // map.put("commentId",Long.valueOf(map.get("commentId").toString()));
       List commentLikeList =  newsService.checkCommentLike(map);  //判断当前新闻的当前评论的当前用户的评论是否存在
        System.out.println(commentLikeList.size());
       if(commentLikeList.size() != 0){
           //有这个点赞记录
           return R.ok("",100).put("data",1);
       }
        return R.ok("",100).put("data",0);
    }

    @GetMapping("/news/getNewsType")
    @ApiOperation("获取新闻分类")
    public R notToken(){
        List l=newsService.getNewsType();
        return R.ok().put("data", l);
    }



}
